import sys
import os
from wav_codec import CodecConfig, WAV_OK, wav_compress, wav_decompress

def read_file(filename):
    """Read a file's content into a bytes object"""
    try:
        with open(filename, 'rb') as f:
            data = f.read()
        return data
    except Exception as e:
        print(f"Error opening file: {filename}")
        print(str(e))
        return None

def write_file(filename, data):
    """Write bytes data to a file"""
    try:
        with open(filename, 'wb') as f:
            f.write(data)
        return 0
    except Exception as e:
        print(f"Error writing to file: {filename}")
        print(str(e))
        return -1

def compress_wav_file(input_file, output_file):
    """Compress a WAV file to a compressed file"""
    # Read WAV file
    wav_data = read_file(input_file)
    if wav_data is None:
        return 1

    print(f"Original WAV file size: {len(wav_data)} bytes")

    # Initialize compression config
    config = CodecConfig()
    
    # Compress WAV data
    compressed_data, result = wav_compress(wav_data, config)
    
    if result != WAV_OK:
        print(f"Compression failed, error code: {result}")
        return 1
    
    print(f"Compressed size: {len(compressed_data)} bytes ({len(compressed_data) * 100.0 / len(wav_data):.2f}%)")
    
    # Save compressed data
    if write_file(output_file, compressed_data) != 0:
        return 1
    
    print("Compression completed!")
    return 0

def decompress_wav_file(input_file, output_file):
    """Decompress a compressed file to a WAV file"""
    # Read compressed file
    compressed_data = read_file(input_file)
    if compressed_data is None:
        return 1
        
    print(f"Compressed file size: {len(compressed_data)} bytes")
    
    # Decompress data
    decompressed_data, result = wav_decompress(compressed_data)
    
    if result != WAV_OK:
        print(f"Decompression failed, error code: {result}")
        return 1
    
    print(f"Decompressed size: {len(decompressed_data)} bytes")
    
    # Save decompressed data
    if write_file(output_file, decompressed_data) != 0:
        return 1
    
    print("Decompression completed!")
    return 0

def show_usage():
    """Display usage information"""
    print(f"Usage:")
    print(f"  Compress:   {sys.argv[0]} -c <input WAV file> <compressed output file>")
    print(f"  Decompress: {sys.argv[0]} -d <input compressed file> <decompressed output WAV file>")

def main():
    # Check command line arguments
    if len(sys.argv) != 4:
        show_usage()
        return 1
        
    # Determine operation type
    if sys.argv[1] == "-c":
        # Compression mode
        return compress_wav_file(sys.argv[2], sys.argv[3])
    elif sys.argv[1] == "-d":
        # Decompression mode
        return decompress_wav_file(sys.argv[2], sys.argv[3])
    else:
        # Invalid operation
        show_usage()
        return 1

if __name__ == "__main__":
    sys.exit(main()) 